package com.wrial.simple;
/*
 * @Author  Wrial
 * @Date Created in 17:21 2020/3/29
 * @Description 二叉树的层次遍历 II
给定二叉树 [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7

[
  [15,7],
  [9,20],
  [3]
]
 */

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class LeetCode_107 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    List<List<Integer>> ans = new LinkedList<>();
    Deque<TreeNode> deque = new LinkedList<>();

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root == null) return ans;
        deque.offer(root);

        List<Integer> submit = new ArrayList();
        TreeNode lastLevelNode = deque.peekLast();
        while (!deque.isEmpty()) {
            TreeNode node = deque.poll();
            submit.add(node.val);

            if (node.left != null) deque.offer(node.left);
            if (node.right != null) deque.offer(node.right);
            if (node == lastLevelNode) {
                lastLevelNode = deque.peekLast();
                ans.add(0, submit);
                submit = new ArrayList<>();
            }
        }

        return ans;
    }
}
